package com.gis.servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.gis.bean.User;
import com.gis.util.Constant;
import com.gis.util.JDBCUtils;
import com.gis.util.ResponseUtil;
import com.gis.util.RestResponse;

import cn.hutool.crypto.digest.DigestUtil;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
	QueryRunner qr = new QueryRunner(JDBCUtils.getC3p0DateSource());

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		Integer age = Integer.valueOf(req.getParameter("age"));
		String phone = req.getParameter("phone");
		String address = req.getParameter("address");
		String gender = req.getParameter("gender");
		String email = req.getParameter("email");
		String realname = req.getParameter("realname");
		
		try {
			// 先查询用户名是否重复
			Long count = qr.query("select count(1) from tb_user where username = ?", new ScalarHandler<Long>(1), username);
			if(count >= 1) {
				ResponseUtil.writeJson(resp, RestResponse.fail(Constant.USER_EXIST));
				return;
			}
			// 将数据存入数据库之中,密码使用 MD5 加密
			String sql = "insert into tb_user (username, password, age, phone, address, gender, email, realname) values(?,?,?,?,?,?,?,?)";
			int update = qr.update(sql, username, DigestUtil.md5Hex(password), age, phone, address, gender, email, realname);
			// 查询出刚刚插入的用户的id
			String sql2 = "select * from tb_user where username = ?";
			List<User> userIdList = qr.execute(sql2,new BeanHandler<User>(User.class), username);

			// 用户赋予角色
			String sql3 = "insert into tb_role_user (user_id, role_id) value(?,?)";
			int i = qr.update(sql3, userIdList.get(0).getId(), 2);
			
			if (update == 0 || i == 0) {
				ResponseUtil.writeJson(resp, RestResponse.fail(Constant.REGISTER_FAILED));
				return;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

		ResponseUtil.writeJson(resp, RestResponse.success(Constant.REGISTER_SUCCESS));
		return;
	}

}
